package vn.com.aptech.msh.utils;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author trietto
 */
public class MD5Utility {

    public static String hash(String source) throws NoSuchAlgorithmException {
        MessageDigest m = MessageDigest.getInstance("MD5");
        byte[] data = source.getBytes();
        m.update(data, 0, data.length);
        BigInteger i = new BigInteger(1, m.digest());
        return String.format("%1$032X", i);
    }

    public static boolean compare(String source, String hashed) {
        if (source == null || hashed == null) {
            return false;
        } else {
            try {
                return hash(source).equalsIgnoreCase(hashed);
            } catch (NoSuchAlgorithmException ex) {
                Logger.getLogger(MD5Utility.class.getName()).log(Level.SEVERE, null, ex);
                return false;
            }
        }
    }
}
